/*
 *所有关于Overtime类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*OvertimeService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.System.IRepositories;
using System.Collections.Generic;
using System;
using VOL.Core.DBManager;
using Dm.filter.log;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using System.IO;
using VOL.Core.Configuration;

namespace VOL.System.Services
{
    public partial class OvertimeService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IOvertimeRepository _repository;//访问数据库
        private WebResponseContent Response { get; set; }

        [ActivatorUtilitiesConstructor]
        public OvertimeService(
            IOvertimeRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        public override WebResponseContent Import(List<IFormFile> files)
        {
            if (files == null || files.Count == 0)
                return new WebResponseContent { Status = true, Message = "请选择上传的文件" };
            Microsoft.AspNetCore.Http.IFormFile formFile = files[0];
            string dicPath = $"Upload/{DateTime.Now.ToString("yyyMMdd")}/{typeof(T).Name}/".MapPath();
            if (!Directory.Exists(dicPath)) Directory.CreateDirectory(dicPath);
            dicPath = $"{dicPath}{Guid.NewGuid().ToString()}_{formFile.FileName}";

            using (var stream = new FileStream(dicPath, FileMode.Create))
            {
                formFile.CopyTo(stream);
            }
            try
            {
                //2022.06.20增加原生excel读取方法(导入时可以自定义读取excel内容)
                //Response = EPPlusHelper.ReadToDataTable<T>(dicPath, DownLoadTemplateColumns, GetIgnoreTemplate(), readValue: ImportOnReadCellValue, ignoreSelectValidationColumns: ImportIgnoreSelectValidationColumns);
            }
            catch (Exception ex)
            {
                Response.Error("未能处理导入的文件,请检查导入的文件是否正确");
                string msg = $"表{typeof(T).GetEntityTableCnName()}导入失败{ex.Message + ex.InnerException?.Message}";
                Console.WriteLine(msg);

            }
            if (CheckResponseResult()) return Response;

            List<T> list = Response.Data as List<T>;
            List<Overtime> OvertimeList = Response.Data as List<Overtime>;

            // ImportOnExecuted( list, formFile.FileName);
            ////ImportHelper ih = new ImportHelper();

            // if (formFile.FileName.Contains("加班申请"))
            // {
            //     List<Overtime> OvertimeList = Response.Data as List<Overtime>;
            //     string message = ih.CheckOvertimeImport(formFile.FileName,OvertimeList);

            //     if (!(string.IsNullOrEmpty(message)))
            //     {
            //         Response.Error(message); return Response;
            //     }


            // }

            string message = "";
            int Row = 1;
            List<int> Rows = new List<int>();
            var dapper = DBServerProvider.GetSqlDapper();
            string departname = OvertimeList[0].departname.ToString();
            string sql = $"select * from overtime_rule where departname = '{departname}'";
            var otr = dapper.QueryFirst<Overtime_rule>(sql, null);
            foreach (var item in OvertimeList)
            {
                DateTime starttime = Convert.ToDateTime(item.starttime);
                DateTime endtime = Convert.ToDateTime(item.endtime);
                //int hours = endtime.Subtract(starttime).Hours;

                TimeSpan timeSpan = endtime - starttime;
                int hours = (int)timeSpan.TotalHours;



                if (Convert.ToInt32(otr.hours) < hours)
                {
                    Rows.Add(Row);

                }
                Row++;
            }

            if (Rows.Count > 0)
            {
                message += "第";
                foreach (var item in Rows)
                {
                    message += item;
                    message += "，";
                }
                message += " 行时间填写不符合规范";
            }







            //Response = ImportOnExecuting.Invoke(list);
            if (CheckResponseResult()) return Response;

            return Response.OK("文件上传成功");

        }


        private bool CheckResponseResult()
        {
            return !Response.Status || Response.Code == "-1";
        }

        private List<string> GetIgnoreTemplate()
        {
            //忽略创建人、修改人、审核等字段
            List<string> ignoreTemplate = UserIgnoreFields.ToList();
            ignoreTemplate.AddRange(auditFields.ToList());
            return ignoreTemplate;
        }
        private static string[] _userIgnoreFields { get; set; }

        private static string[] UserIgnoreFields
        {
            get
            {
                if (_userIgnoreFields != null) return _userIgnoreFields;
                List<string> fields = new List<string>();
                fields.AddRange(CreateFields);
                fields.AddRange(ModifyFields);
                _userIgnoreFields = fields.ToArray();
                return _userIgnoreFields;
            }
        }

        private static string[] _createFields { get; set; }
        private static string[] CreateFields
        {
            get
            {
                if (_createFields != null) return _createFields;
                _createFields = AppSetting.CreateMember.GetType().GetProperties()
                    .Select(x => x.GetValue(AppSetting.CreateMember)?.ToString())
                    .Where(w => !string.IsNullOrEmpty(w)).ToArray();
                return _createFields;
            }
        }

        private static string[] _modifyFields { get; set; }
        private static string[] ModifyFields
        {
            get
            {
                if (_modifyFields != null) return _modifyFields;
                _modifyFields = AppSetting.ModifyMember.GetType().GetProperties()
                    .Select(x => x.GetValue(AppSetting.ModifyMember)?.ToString())
                    .Where(w => !string.IsNullOrEmpty(w)).ToArray();
                return _modifyFields;
            }
        }

        private static string[] auditFields = new string[] { "auditid", "auditstatus", "auditor", "auditdate", "auditreason" };
    }
}
